package com.leyantech.ecp.agenx.common.di;

import com.leyantech.utility.constructs.Constructs;

import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import io.vertx.core.json.JsonObject;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-12-08.
 */
public class CuratorFactory {

  public static final CuratorFramework curatorFramework = getCuratorFramework();

  private static CuratorFramework getCuratorFramework() {

    final ConfigFile configFile = ConfigService.getConfigFile("zookeeper", ConfigFileFormat.JSON);
    final JsonObject conf = configFile.hasContent()
        ? new JsonObject(configFile.getContent())
        : new JsonObject();

    final JsonObject defObject = new JsonObject();
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(
        conf.getJsonObject("retry", defObject).getInteger("initialSleepTime", 1000),
        conf.getJsonObject("retry", defObject).getInteger("maxTimes", 5),
        conf.getJsonObject("retry", defObject).getInteger("intervalTimes", 10000)
    );

    final String hosts = conf.getString("zookeeperHosts");

    final CuratorFramework curator = CuratorFrameworkFactory.builder()
        .connectString(hosts)
        .namespace(conf.getString("rootPath", Constructs.getAppNameOrDefault() + "-vertx"))
        .sessionTimeoutMs(conf.getInteger("sessionTimeout", 20000))
        .connectionTimeoutMs(conf.getInteger("connectTimeout", 3000))
        .retryPolicy(retryPolicy)
        .build();

    curator.start();
    return curator;
  }

}
